package com.example.universitylibraryback.pipeline.filter;

import com.example.universitylibraryback.pipeline.BorrowContext;
import com.example.universitylibraryback.pipeline.Filter;
import java.util.concurrent.BlockingQueue;
import java.util.Date;

/**
 * 借阅记录生成过滤器
 * 负责生成借阅记录ID和设置借阅日期、到期日期
 */
public class BorrowRecordGenerateFilter implements Filter<BorrowContext>, Runnable {
    private BlockingQueue<BorrowContext> inputQueue;
    private BlockingQueue<BorrowContext> outputQueue;

    @Override
    public void process(BlockingQueue<BorrowContext> inputQueue, BlockingQueue<BorrowContext> outputQueue) throws InterruptedException {
        this.inputQueue = inputQueue;
        this.outputQueue = outputQueue;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                BorrowContext context = inputQueue.take();
                if (!context.isValid()) {
                    outputQueue.put(context);
                    continue;
                }
                String recordId = "BR_" + System.currentTimeMillis();
                Date borrowDate = new Date();
                Date dueDate = new Date(borrowDate.getTime() + 30L * 24 * 60 * 60 * 1000);
                context.setBorrowRecordId(recordId);
                context.setBorrowDate(borrowDate);
                context.setDueDate(dueDate);
                context.setErrorMsg("借阅记录生成成功，到期日期：" + dueDate);
                outputQueue.put(context);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("BorrowRecordGenerateFilter中断");
        }
    }
}
